﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Models;
using System.Configuration;

namespace DAL
{
   public class SqlDBHelper
    {
        //private static string connString = "server=.;database=Takeout;uid=sa;pwd=123456";
        public static readonly string connString = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
        //查询
        public static DataTable GetDataTable(string sql, params SqlParameter[] para)
        {
            DataTable dt = new DataTable();
            using (SqlConnection conn = new SqlConnection(connString))
            {
                using (SqlCommand com = new SqlCommand(sql, conn))
                {
                    if (para != null)
                    {
                        com.Parameters.AddRange(para);
                    }
                    using (SqlDataAdapter sda = new SqlDataAdapter(com))
                    {
                        sda.Fill(dt);
                    }
                }
            }
            return dt;
        }
        //增删改
        public static int ExecuteNonQuery(string sql, params SqlParameter[] para)
        {
            using (SqlConnection conn = new SqlConnection(connString))
            {
                using (SqlCommand com = new SqlCommand(sql, conn))
                {
                    if (para != null)
                    {
                        conn.Open();
                        com.Parameters.AddRange(para);
                    }

                    return com.ExecuteNonQuery();
                    
                   
                }
            }

        }
        //执行聚合函数
        /// <summary>
        /// 执行聚合函数
        /// </summary>
        /// <param name="sql">带聚合函数的sql</param>
        /// <returns>一行一列的结果</returns>
        public static object ExecuteScalar(string sql)
        {
            //连接数据库
            SqlConnection conn = new SqlConnection(connString);
            conn.Open();
            //创建对象
            SqlCommand com = new SqlCommand(sql, conn);
            //返回增删改结果
            return com.ExecuteScalar();
        }
        //逐行读取增删改
        public static SqlDataReader GetReader(string sql)
        {
            SqlConnection coon = new SqlConnection(connString);
            SqlCommand com = new SqlCommand(sql, coon);
            coon.Open();
            return com.ExecuteReader();
        }
      
    }
}
